﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Web;

namespace MVCPlugin.Utility
{
    public class LocalizedUrlHelper
    {
        private string m_ApplicationPath;

        private string m_RelativePath;

        public LocalizedUrlHelper(HttpRequest httpRequest, bool rawUrl = false)
            : this(httpRequest.ApplicationPath, rawUrl ? httpRequest.RawUrl : httpRequest.Path, rawUrl)
        {

        }

        public LocalizedUrlHelper(HttpRequestBase httpRequest, bool rawUrl = false)
            : this(httpRequest.ApplicationPath, rawUrl ? httpRequest.RawUrl : httpRequest.Path, rawUrl)
        {

        }

        public LocalizedUrlHelper(string applicationPath, string relativePath, bool rawUrl = false)
        {
            this.m_ApplicationPath = applicationPath;
            if (rawUrl)
            {
                this.m_RelativePath = RemoveApplicationPathFromRawUrl(relativePath).TrimStart('~', '/');
            }
            else
            {
                this.m_RelativePath = relativePath.TrimStart('~', '/');
            }
        }


        public string GetRelativePath()
        {
            return this.m_RelativePath;
        }

        public string GetAbsolutePath()
        {
            string path = this.m_ApplicationPath.TrimEnd('/') + "/";
            path = path + this.GetRelativePath();
            if (path.Length > 1 && path[0] != '/')
            {
                path = "/" + path;
            }
            return path;
        }

        private string RemoveApplicationPathFromRawUrl(string rawUrl)
        {
            if (rawUrl.Length == m_ApplicationPath.Length)
            {
                return "/";
            }

            var result = rawUrl.Substring(m_ApplicationPath.Length);
            // raw url always starts with '/'
            if (!result.StartsWith("/"))
            {
                result = "/" + result;
            }
            return result;
        }       
    }
}
